package com.qiantu.phone.ui.fragment.device;

import android.util.Log;
import android.view.View;

import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleOwner;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hjq.base.BaseAdapter;
import com.hjq.http.listener.HttpCallback;
import com.hjq.toast.ToastUtils;
import com.qiantu.api.db.LLDeviceDBManager;
import com.qiantu.api.entity.DeviceModeValue;
import com.qiantu.api.entity.LinkageBean;
import com.qiantu.api.entity.UniversalDeviceAction;
import com.qiantu.api.entity.UniversalDeviceData;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.ui.adapter.DeviceModeLabelAdapter;
import com.qiantu.phone.ui.adapter.DeviceModeValueAdapter;
import com.qiantu.phone.ui.uiutil.LLDeviceUtil;
import com.qiantu.phone.widget.AirConditionerSeekBar;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

public class UniversalAirFragment extends BaseDeviceFragment{
    private AirConditionerSeekBar airConditionerSeekBar;
    private RecyclerView modeRecyclerView;
    private RecyclerView modeValueRecyclerView;
    private DeviceModeLabelAdapter mDeviceModeLabelAdapter;
    private DeviceModeValueAdapter mDeviceModeValueAdapter;
//    private ControlDataAirConditionerBean airConditionerInfo;
//    private ControlDataAirConditionerBean.ControlData controlData;
    private String selectedLabel;
    private List<DeviceModeValue> powers;
    private List<DeviceModeValue> modes;
    private List<DeviceModeValue> speeds;
    private List<DeviceModeValue> directions;
    private UniversalDeviceData temperature;


    public static UniversalAirFragment newInstance() {
        UniversalAirFragment fragment = new UniversalAirFragment();
        return fragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_air_conditioner;
    }

    @Override
    protected void initView() {
        super.initView();
        airConditionerSeekBar = findViewById(R.id.air_conditioner_seek_bar);
        modeRecyclerView = findViewById(R.id.mode_recycler_view);
        modeValueRecyclerView = findViewById(R.id.mode_value_recycler_view);
        airConditionerSeekBar.setOnChangeListener(new AirConditionerSeekBar.OnChangeListener() {
            @Override
            public void onValueChanged(float value) {}

            @Override
            public void onStopTrackingTouch(float value) {
//                DeviceState deviceState = mDevice.getStateData();
//                Integer temperature = deviceState.getStatus().getTemperature();
//                if (Float.valueOf(temperature) != value) {
//                    temperatureOperation((int)value);
//                }
                temperatureOperation((int)value);
            }

            @Override
            public void onSwitch(boolean isOpen) {
//                setStatusBySwitch(isOpen);
                airConditionerSeekBar.setOpenState(!isOpen);
                switchOperation();
            }
        });
        getData();
    }

    private void getData(){
        LLHttpManager.getDeviceTgpactions((LifecycleOwner) getContext(), mDevice.getDeviceSerialNo(), new HttpCallback<HttpData<UniversalDeviceAction>>(null) {
            @Override
            public void onStart(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity) {
                    ((AppActivity) getContext()).showDialog("执行中...");
                }
            }

            @Override
            public void onSucceed(HttpData<UniversalDeviceAction> result) {
                rebuildData(result.getData().getTgpActions());
            }

            @Override
            public void onFail(Exception e) {
                if(getContext() != null && getContext() instanceof AppActivity) {
                    ToastUtils.show(R.string.exec_failure);
                }
            }

            @Override
            public void onEnd(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity) {
                    ((AppActivity) getContext()).hideDialog();
                }
            }
        });
    }

    private void rebuildData(List<UniversalDeviceData> actionDtos){
        powers = new ArrayList<>();
        modes = new ArrayList<>();
        speeds = new ArrayList<>();
        directions = new ArrayList<>();

        for(UniversalDeviceData actionDto : actionDtos){
            if(!actionDto.getEnable()){
                continue;
            }
            DeviceModeValue modeValue = new DeviceModeValue();
            modeValue.setName(actionDto.getRangeName());
            if(actionDto.getRangeIdentifier() != null){
                int value = Integer.parseInt(actionDto.getRangeIdentifier());
                modeValue.setValue(value);
            }else{
                modeValue.setValue(0);
            }
            modeValue.setSort(actionDto.getSort());
            modeValue.setImage(actionDto.getDisplayImage());
            if(actionDto.getActionIdentifier().equals("mode")){
                modes.add(modeValue);
            }else if(actionDto.getActionIdentifier().equals("windspeed")){
                speeds.add(modeValue);
            }else if(actionDto.getActionIdentifier().equals("temperature")){
                temperature = actionDto;
            }else if(actionDto.getActionIdentifier().equals("power")){
                powers.add(modeValue);
            }else if(actionDto.getActionIdentifier().equals("winddirection")){
                directions.add(modeValue);
            }
        }
        modes.sort(new Comparator<DeviceModeValue>(){
            @Override
            public int compare(DeviceModeValue o1, DeviceModeValue o2) {
                return o1.getSort() < o2.getSort() ? -1 : 1;
            }
        });
        speeds.sort(new Comparator<DeviceModeValue>(){
            @Override
            public int compare(DeviceModeValue o1, DeviceModeValue o2) {
                return o1.getSort() < o2.getSort() ? -1 : 1;
            }
        });
        directions.sort(new Comparator<DeviceModeValue>(){
            @Override
            public int compare(DeviceModeValue o1, DeviceModeValue o2) {
                return o1.getSort() < o2.getSort() ? -1 : 1;
            }
        });
        buildView();
    }

    private void buildView(){
        List<String> modeList = new ArrayList<>();
        airConditionerSeekBar.setMinMax(temperature.getMin(), temperature.getMax());
        if (modes.size() > 0) {
            modeList.add(getString(R.string.mode));
        }
        if (speeds.size() > 0) {
            modeList.add(getString(R.string.wind_speed));
        }
        if (directions.size() > 0) {
            modeList.add(getString(R.string.wind_direction));
        }
        if (modeList.size() == 0){
            return;
        }
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), modeList.size());
        modeRecyclerView.setLayoutManager(gridLayoutManager);
        mDeviceModeLabelAdapter = new DeviceModeLabelAdapter(getContext());
        mDeviceModeLabelAdapter.setData(modeList);
        mDeviceModeLabelAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
                selectedLabel = mDeviceModeLabelAdapter.getData().get(position);
                mDeviceModeLabelAdapter.selectItem(position);
                if (selectedLabel.equals(getString(R.string.mode))) {
                    mDeviceModeValueAdapter.setData(modes);
                    selectValue(true, mDevice.getMode());
                } else if (selectedLabel.equals(getString(R.string.wind_speed))) {
                    mDeviceModeValueAdapter.setData(speeds);
                    selectValue(false, mDevice.getWindSpeed());
                } else if (selectedLabel.equals(getString(R.string.wind_direction))) {
                    mDeviceModeValueAdapter.setData(directions);
                    selectValue(false, mDevice.getWindDirection());
                }
            }
        });
        modeRecyclerView.setAdapter(mDeviceModeLabelAdapter);
        mDeviceModeLabelAdapter.selectItem(0);
        selectedLabel = modeList.get(0);
        mDeviceModeValueAdapter = new DeviceModeValueAdapter(getContext());
        if(modes.size() != 0){
            mDeviceModeValueAdapter.setData(modes);
        }else if(speeds.size() != 0){
            mDeviceModeValueAdapter.setData(speeds);
        }else{
            mDeviceModeValueAdapter.setData(directions);
        }

        mDeviceModeValueAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
                if(!airConditionerSeekBar.isOpen()){
                    ToastUtils.show(R.string.device_off_disable);
                    return;
                }
                boolean isMode = false;
                DeviceModeValue valueBean = mDeviceModeValueAdapter.getData().get(position);
                if (selectedLabel.equals(getString(R.string.mode))) {
                    airConditionerSeekBar.setModeName(valueBean.getName());
                    isMode = true;
                    modeOperation(valueBean.getValue());
                } else if (selectedLabel.equals(getString(R.string.wind_speed))) {
                    isMode = false;
                    windSpeedOperation(valueBean.getValue());
                }
                //切换模式需要更新颜色
                mDeviceModeValueAdapter.selectItem(isMode, position);
            }
        });
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(RecyclerView.HORIZONTAL);
        modeValueRecyclerView.setLayoutManager(linearLayoutManager);
        modeValueRecyclerView.setAdapter(mDeviceModeValueAdapter);
        updateView();
    }

    private void switchOperation() {
        Log.i("lzxlzxlzx", "switchOperation isOpen:" + airConditionerSeekBar.isOpen());
        Map<String, Object> option = new HashMap<>();
        option.put(LLDeviceUtil.POWER, airConditionerSeekBar.isOpen() ? 0 : 1);
        Map<String, Object> status = new HashMap<>();
        status.put(STATUS, option);
        LLHttpManager.operationDevice((LifecycleOwner) getContext(), mDevice.getDeviceSerialNo(), status, new HttpCallback<HttpData<Void>>(null) {
            @Override
            public void onStart(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity){
                    ((AppActivity) getContext()).showDialog("执行中...");
                }
            }

            @Override
            public void onSucceed(HttpData<Void> result) {
                mDevice.setIsOpen(!airConditionerSeekBar.isOpen());
                setStatusBySwitch(mDevice.getIsOpen());
                Log.i("lzxlzxlzx", "switchOperation onSucceed isOpen:" + airConditionerSeekBar.isOpen());
                LLDeviceDBManager.getInstance(getContext()).put(mDevice);
                refreshDeviceStateByLocal();
            }

            @Override
            public void onFail(Exception e) {
                ToastUtils.show(R.string.exec_failure);
            }

            @Override
            public void onEnd(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity){
                    ((AppActivity) getContext()).hideDialog();
                }
            }
        });
    }

    private void temperatureOperation(int temperature) {
        if(!mDevice.getIsOpen()){
            ToastUtils.show(R.string.device_off_disable);
            return;
        }
        Map<String, Object> option = new HashMap<>();
        option.put(LLDeviceUtil.TEMPERATURE, temperature);
        Map<String, Object> status = new HashMap<>();
        status.put(STATUS, option);
        LLHttpManager.operationDevice((LifecycleOwner) getContext(), mDevice.getDeviceSerialNo(), status, new HttpCallback<HttpData<Void>>(null) {
            @Override
            public void onStart(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity){
                    ((AppActivity) getContext()).showDialog("执行中...");
                }
            }

            @Override
            public void onSucceed(HttpData<Void> result) {
                mDevice.setTemperature(temperature);
                LLDeviceDBManager.getInstance(getContext()).put(mDevice);
                refreshDeviceStateByLocal();
            }

            @Override
            public void onFail(Exception e) {
                //失败取设备值
                airConditionerSeekBar.setTemp(Float.valueOf(mDevice.getTemperature()));
                ToastUtils.show(R.string.exec_failure);
            }

            @Override
            public void onEnd(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity){
                    ((AppActivity) getContext()).hideDialog();
                }
            }
        });
    }

    private void modeOperation(int mode) {
        Map<String, Object> option = new HashMap<>();
        option.put(LLDeviceUtil.MODE, mode);
        Map<String, Object> status = new HashMap<>();
        status.put(STATUS, option);
        LLHttpManager.operationDevice((LifecycleOwner) getContext(), mDevice.getDeviceSerialNo(), status, new HttpCallback<HttpData<Void>>(null) {
            @Override
            public void onStart(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity){
                    ((AppActivity) getContext()).showDialog("执行中...");
                }
            }

            @Override
            public void onSucceed(HttpData<Void> result) {
                mDevice.setMode(mode);
                LLDeviceDBManager.getInstance(getContext()).put(mDevice);
                refreshDeviceStateByLocal();
            }

            @Override
            public void onFail(Exception e) {
                //失败取设备值
                setModeName();
                setValueByLabel();
                ToastUtils.show(R.string.exec_failure);
            }

            @Override
            public void onEnd(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity) {
                    ((AppActivity) getContext()).hideDialog();
                }
            }
        });
    }

    private void windSpeedOperation(int windSpeed) {
        Map<String, Object> option = new HashMap<>();
        option.put(LLDeviceUtil.WIND_SPEED, windSpeed);
        Map<String, Object> status = new HashMap<>();
        status.put(STATUS, option);
        LLHttpManager.operationDevice((LifecycleOwner) getContext(), mDevice.getDeviceSerialNo(), status, new HttpCallback<HttpData<Void>>(null) {
            @Override
            public void onStart(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity){
                    ((AppActivity) getContext()).showDialog("执行中...");
                }
            }

            @Override
            public void onSucceed(HttpData<Void> result) {
                mDevice.setWindSpeed(windSpeed);
                LLDeviceDBManager.getInstance(getContext()).put(mDevice);
                refreshDeviceStateByLocal();
            }

            @Override
            public void onFail(Exception e) {
                //失败取设备值
                setValueByLabel();
                ToastUtils.show(R.string.exec_failure);
            }

            @Override
            public void onEnd(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity) {
                    ((AppActivity) getContext()).hideDialog();
                }
            }
        });
    }

    private void setValueByLabel(){
        if (selectedLabel.equals(getString(R.string.mode))) {
            setModeName();
            selectValue(true, mDevice.getMode());
        } else if (selectedLabel.equals(getString(R.string.wind_speed))) {
            selectValue(false, mDevice.getWindSpeed());
        }
    }

    private void selectValue(boolean isMode, Integer value){
        //设备关闭不设置设置缓存里的模式
        if(!airConditionerSeekBar.isOpen()){
            return;
        }
        for(int i=0; i<mDeviceModeValueAdapter.getData().size(); i++){
            if(mDeviceModeValueAdapter.getData().get(i).getValue() == value){
                mDeviceModeValueAdapter.selectItem(isMode, i);
                break;
            }
        }
    }

    private void setStatusBySwitch(boolean isOpen){
        airConditionerSeekBar.setOpenState(isOpen);
        if(isOpen){
            setValueByLabel();
        }else{
            mDeviceModeValueAdapter.clearSelected();
        }
    }

    private void setModeName(){
        for(DeviceModeValue valueBean : modes){
            if(mDevice.getMode().equals(valueBean.getValue() )){
                airConditionerSeekBar.setModeName(valueBean.getName());
                break;
            }
        }
    }

    protected void updateView() {
        super.updateView();
//        if (mDevice.isIsOnline()) {
        airConditionerSeekBar.setEnabled(true);
        airConditionerSeekBar.setTemp(Float.valueOf(mDevice.getTemperature()));
        setModeName();
        setStatusBySwitch(mDevice.getIsOpen());
//        } else {
//            airConditionerSeekBar.setEnabled(false);
//            setStatusBySwitch(false);
//        }
    }

    @Override
    public void onResume() {
        super.onResume();
        getData();
    }


}
